define(['jquery', 'bootstrap', 'backend', 'table', 'form', '../../template-web'], function ($, undefined, Backend, Table, Form, template) {
    let rule = template.defaults.rules[1];
    rule.test = new RegExp(rule.test.source.replace('{{', '{{#'));
    
    let setData = function (template_id, elem_id, data) {
        let html = template(template_id, data);
        document.getElementById(elem_id).innerHTML = html;
    }

    //获取日期
    let getTime = function (type = null) {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth();
        var day = now.getDay(); //返回星期几的某一天;

        type = day == 0 ? type + 6 : type + (day - 1);

        year = month == 1 && now.getDate() - type <= 0 ? year - 1 : year; //周一为上一年的12月份的
        var t_date = now.getDate() - type;
        now.setDate(now.getDate() - type);
        var date = now.getDate();
        month = year < now.getFullYear() ? 12 : (date <= t_date ? month + 1 : month);   //特殊的2月份

        var time = year + "/" + (month < 10 ? ('0' + month) : month) + "/" + (date < 10 ? ('0' + date) : date);
        return time;
    };


    //弹出层宽高
    var area = Fast.config.openArea != undefined ? Fast.config.openArea : [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%'];

    //获取弹出层数据
    let getIframeData = function (index, id = null) {
        var layero = Layer.getChildFrame('html', index);
        return layero.find(id).val();
    }
    //数据验证提示
    let tips = function (index, keys) {
        var layero = Layer.getChildFrame('html', index);
        var length = keys.length;
        for (var i = 0; i < length; i ++) {
            var data_validator = layero.find('#c-'+ keys[i]).attr('data-validator');
            var value = layero.find('#c-'+ keys[i]).val();
            if (data_validator == 'required' && !value) {
                layer.msg(__(keys[i].charAt(0).toUpperCase() + keys[i].slice(1)) + '不能为空', {icon: 2, time: 1000});
                return false;
            }
        }
        return true;
    }


    //添加课程
    $('#tbody').on('click', '.btn-add', function () {

        var date = $(this).parent().attr('data-date');
        var class_id = $('#classes').val();

        var url = Fast.api.fixurl('chase/course/add');
        url = url + (url.indexOf("?") > -1 ? "&" : "?") + "dialog=1";
        Layer.open({
            title: '添加课程',
            area: area,
            type: 2,
            shadeClose: true,
            shade: false,
            content: 'course/add?date=' + date + '&class_id=' + class_id,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                var data = {
                    time: getIframeData(index, '#c-time'),
                    timetable_cn: getIframeData(index, '#c-timetable_cn'),
                    timetable_en: getIframeData(index, '#c-timetable_en'),
                    class_id: getIframeData(index, '#c-class_id'),
                    teacher_id: getIframeData(index, '#c-teacher_id'),
                    date: getIframeData(index, '#c-date'),
                };
                //验证
               if (tips(index, Object.keys(data))) {
                   $.ajax({
                       url: 'chase/course/create',
                       method: 'POST',
                       data: data,
                       success: function (res) {
                           if (res) {
                               layer.msg('添加成功', {icon: 1, time: 1000}, function () {
                                   layer.close(index);
                                   getCourse();
                               });
                           } else {
                               layer.msg('添加失败', {icon: 2});
                           }
                       }
                   });
               }


            }
        });
    })


    //编辑
    $('#tbody').on('click', '.btn-edit', function () {
        var ids = $(this).attr('data-id');
        Fast.api.open('chase/course/edit/ids/' + ids, '编辑课程', '');
    })

    $('#this-week').val(getTime(0) + ' - ' + getTime(-6))
    $('#this-week').data('time', getTime(0) + ' - ' + getTime(-6))


    let t = function(id) {
        var time = '';
        switch (id) {
            case 'this-week':
                time = $('#this-week').val()
                break;
            case 'last-week':
                time = getTime(7) + ' - ' + getTime(1)
                break;
            case 'next-week':
                time = getTime(-7) + ' - ' + getTime(-13)
                break;
        }
        return time
    }

    //表格数据
    let getCourse = function (id = 'this-week') {
        //第一次进来默认第一个班级的数据
        var class_id = $('#classes').val();
        var teacher_id = $('#teacher').val();
        //默认本周时间
        var time = t(id)

        $.ajax({
            url: 'chase/course/course',
            type: 'GET',
            data: {
                class_id: class_id,
                teacher_id: teacher_id,
                time: time
            },
            success: function (res) {
                setData('temp-thead', 'thead', res);
                setData('temp-tbody', 'tbody', res);
                $('#tbody .am').css({"height": $('#tbody .am').height()+'px', "line-height": $('#tbody .am').height()+'px'});
                $('#tbody .pm').css({"height": $('#tbody .pm').height()+'px', "line-height": $('#tbody .pm').height()+'px'});
            }
        });
    }
    //切换按钮
    $('#tbody').on('click', '.btn-change', function () {
        var ids = $(this).attr('data-id');
        $.ajax({
            url: 'chase/course/toggle/ids/' + ids,
            success: function (res) {
                if (res.error) {
                    layer.alert(res.msg, {icon: 2});
                } else {
                    layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                        getCourse();
                    });

                }
            }
        });
    })

    var Controller = {
        index: function () {

            getCourse();
            //班级
            $('#classes').on('change', function () {
                getCourse();
            });
            //老师
            $('#teacher').on('change', function () {
                getCourse();
            });
            //上周
            $('#last-week').on('click', function () {
                getCourse('last-week');
            })
            //下周
            $('#next-week').on('click', function () {
                getCourse('next-week');
            })
            //本周
            $('#this-week').on('click', function () {
                setInterval(function(){
                    if($('#this-week').data('time')!= $('#this-week').val()){
                        var t = $('#this-week').val().split(' - ')
                        var startTime = t[0].split(' ')[0];
                        var endTime = t[1].split(' ')[0];
                        $('#this-week').val(startTime.replace('-', '/') + ' - ' + endTime.replace('-', '/'))
                        $('#this-week').data('time', startTime.replace('-', '/') + ' - ' + endTime.replace('-', '/'))
                        getCourse();
                        clearInterval();
                    }
                },50)
            })

           
            Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});